﻿using System.Collections;
using System.Collections.Generic;
using System.Text;
using UnityEngine;
using UnityEngine.UI;

public class DebugConsole : MonoBehaviour
{
    [SerializeField] private CanvasGroup _cavGroup;
    [SerializeField] private RectTransform _contentRect;
    [SerializeField] private Text _contentText;
    [SerializeField] private int _maxCount = 600;
    
    private Queue<string> _strQueue;
    private StringBuilder _outputStrBuilder;
    public KeyCode openKey = KeyCode.Tilde;
    public bool active = true;


    private void Awake()
    {
        _strQueue = new Queue<string>(_maxCount + 5);
        _outputStrBuilder = new StringBuilder(8000);
        Application.logMessageReceived += HandleLog;       
    }

    private void Update()
    {
        _contentRect.sizeDelta = new Vector2(_contentRect.sizeDelta.x, _contentText.rectTransform.rect.height);        

        if(Input.GetKeyDown(openKey))
        {
            if(active == true)
            {
                active = false;
            }
            else
            {
                active = true;
            }
        }

        if (active == true)
        {
            _cavGroup.alpha = 1f;
            _cavGroup.blocksRaycasts = true;
        }
        else
        {
            _cavGroup.alpha = 0f;
            _cavGroup.blocksRaycasts = false;
        }
    }

    private void OnDestroy()
    {
        Application.logMessageReceived -= HandleLog;
    }

    private void HandleLog(string logString, string stackTrace, LogType type)
    {
        string str = "---- LogType: " + type + " ----\n" + logString + "\n" + stackTrace + "\n\n";       

        if (_strQueue.Count < _maxCount)
        {
            _outputStrBuilder.Append(str);
            _strQueue.Enqueue(str);
            _contentText.text = _outputStrBuilder.ToString();
        }
        else
        {
            _outputStrBuilder.Remove(0, _strQueue.Dequeue().Length);
            _outputStrBuilder.Append(str);
            _strQueue.Enqueue(str);
            _contentText.text = _outputStrBuilder.ToString();
        }        
    }



}
